package com.cn.wanxi.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;


public class Upload {
    public static void file(HttpServletRequest req) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        System.out.println("开始上传");

//        工厂缓存
        DiskFileItemFactory fu = new DiskFileItemFactory();
        fu.setSizeThreshold(2 * 1024 * 1024);
//        fu.setSizeThreshold(4096);
//        解析文件
        ServletFileUpload upload = new ServletFileUpload(fu);
        upload.setHeaderEncoding("UTF-8");
//        定义一个文件的集合用于装前端传过来的文件
        List<FileItem> fileItems = null;
        try {
            fileItems = upload.parseRequest(req);
//            迭代器:Iterator线程安全
            Iterator<FileItem> iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                item.getString("UTF-8");
                ServletInputStream inputStream = req.getInputStream();
//                这个key目的就是为了req保存数据
                String key = item.getFieldName();

                //忽略其他不是文件域的所有表单信息
//                String name = (String) req.getAttribute("name");
//                String price = (String) req.getAttribute("price");
//                System.out.println(name + "++++++++" + price);
                if (item.isFormField()) {

                    String value = item.getString("UTF-8");
//                    System.out.println(key + "+++" + value);
                    req.setAttribute(key, value);
                } else {
                    String name1 = item.getName();//获取上传的文件名
                    long size = item.getSize();//获取上传的文件大小(字节为单位)
                    if ((name1 == null || name1.equals("")) && size == 0) {
                        continue;//跳到while检查条件
                    }
//                    D:\wanxi\step-4\aa.jpg
                    int end = name1.length();
//从右边网左边数，找到第一个斜杠即得到字符串的下标索引
                    int begin = name1.lastIndexOf("\\");

                    String newname = System.currentTimeMillis() + "---" + name1.substring(begin + 1, end);
                    if (newname.length() == 0) {
                        System.out.println("上传文件导入异常，请重新上传...");
                    } else {
                        try {
//                            String key = item.getFieldName();
                            String path = "D:\\wanxi\\step-4\\canyin04-0301\\web";
                            String loadImg = "/loadImg/";
                            File directory = new File(path + loadImg);
                            if (!directory.exists()) {
                                directory.mkdirs();
                            }
                            //保存文件
                            File savedFile = new File(path + loadImg, newname);//用原文件名，作为上传文件的文件名。“/code”为目标路径
                            item.write(savedFile);
                            item.delete();
                            String outPath = "D:\\wanxi\\step-4\\canyin04-0301\\out\\artifacts\\canyin04_0301_war_exploded\\loadImg";
                            copy(savedFile, outPath, newname);
                            req.setAttribute(key, loadImg + newname);
                            System.out.println("上传结束");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    private static void copy(File file, String path, String fileName) {
        try {
            InputStream inputStream = new FileInputStream(file);
            File directory = new File(path);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            OutputStream outputStream = new FileOutputStream(new File(directory, fileName));
            int leng = 0;
            while (leng != -1) {
                leng = inputStream.read();
                outputStream.write(leng);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
